import React, { Component } from 'react'
import { Form, Input, Button, message } from 'antd'
import { CopyToClipboard } from 'react-copy-to-clipboard'

import { address } from '@/Utils/apiConfig'
import request from '@/Utils/fecth'
import getData from '@/Utils/fecth'

import './index.less'

const { TextArea } = Input
const { license } = address

export default class Register extends Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: false,
      requestCode: '',
    }
  }

  componentDidMount() {
    this.getActivateStatus()
  }

  getActivateStatus = async() => {
    const { status, data = {}} = await getData().get(license.getStatus)
    if (status === 200 && data) {
      this.setState({
        requestCode: data.requestCode,
      })
    }
  }

  // 提交表单
  handleSubmit = async(values) => {
    this.setState({
      loading: true,
    })
    const { status, data = {}} = await request().post(license.activate, values)
    this.setState({
      loading: false,
    })
    if (status === 200 && data.activated) {
      message.success('激活成功')
      setTimeout(() => {
        window.location.href = '/'
      }, 500)
    } else {
      message.error(data.message || '激活失败')
    }
  };

  render() {
    const { loading, requestCode } = this.state
    return (
      <div className="activate_page">
        <div className="login_form">
          <Form
            onFinish={this.handleSubmit}
            className="login_form_box"
            name="login"
            layout="vertical"
            ref={(ref) => (this.form = ref)}
            colon={false}
            hideRequiredMark={true}
          >
            <h1 className="login-title">激    活</h1>
            {
              requestCode &&
              <div className="mb24 requestCode">
                请求码: {requestCode}
                <CopyToClipboard text={requestCode}
                  onCopy={() => message.success('复制成功')}>
                  <Button style={{ marginLeft: 'auto' }} className="com-btn-primary com-normal-btn">复制</Button>
                </CopyToClipboard>
              </div>
            }
            <Form.Item
              name="activateCode"
              label=""
              rules={[{ required: true, message: '请输入您的激活码' }]}
            >
              <TextArea
                className="input"
                placeholder="请输入您的激活码"
                rows={5}
                autoSize={false}
              />
            </Form.Item>
            <Form.Item>
              <Button
                loading={loading}
                type="primary"
                htmlType="submit"
                style={{ width: '100%' }}
                size="large"
              >
                激&nbsp;活
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    )
  }
}
